package cn.zhqr.lib.utils;

import cn.zhqr.common.util.collections.Lists;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by charles on 2019/4/18.
 */
public class ServletKit {

    public static String getQueryString(HttpServletRequest request){
        StringBuilder query_string_sb = new StringBuilder();
        Enumeration<String> param_names = request.getParameterNames();
        while (param_names.hasMoreElements()){
            String param_name = param_names.nextElement();
            query_string_sb.append(param_name).append("=").append(request.getParameter(param_name)).append("&");
        }
        String query_str = query_string_sb.toString();
        if(query_str.endsWith("&")){
            query_str = query_str.substring(0,query_str.length()-1);
        }
        return query_str;
    }

    public static URI getRequestURI(HttpServletRequest request){
        URI uri = URI.create(request.getRequestURL().append("?").append(getQueryString(request)).toString());
        return uri;
    }

    public static String getServerUrl(HttpServletRequest request){
        return request.getScheme()+"://"
                +request.getServerName()
                +(80==request.getServerPort() || 443==request.getServerPort()?"":request.getServerPort());
    }

    public static final List<String> ipHeaders = Lists.arrayList("X-Forwarded-For","X-Real-IP","Proxy-Client-IP","WL-Proxy-Client-IP");
    public static String getIp(HttpServletRequest request){
        String ip = null;
        for(String header : ipHeaders){
            ip = request.getHeader(header);
            if(isValidUrl(ip)){
                return ip;
            }
        }

        if(!isValidUrl(ip)){
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }

    private static boolean isValidUrl(String ip){
        return ip != null && ip.length() > 7 && !"unknown".equalsIgnoreCase(ip);
    }
}
